<?php

namespace App\Http\Controllers\Backend;

use App\Models\Card;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;

class SalesmansController extends Controller
{
    public function index()
    {
        $salesmans = User::with(['cards' => function ($card){
                return $card->orderBy ('id', 'desc')->get();
        }])->get();
        return view('backend.salesmans.index', compact('salesmans'));
    }

    public function create()
    {
        $cards = Card::where('status', true)->whereDoesntHave('user')->get();
        return view('backend.salesmans.create', compact('cards'));
    }

    public function store(Request $request)
    {
        $data = $request->all();
        $card = Card::whereIn('id', $data['my-select'])->get();
        if($card){
            return back()->withErrors('你选择的卡已有用户正在使用,请刷新重试.');
        }
        $user = User::create([
            'name' => $data['name'],
            'password' => Hash::make($data['password']),
            'email' => $data['email'],
            'create'
        ]);
        $user->cards()->attach($data['my-select']);
        session()->flash('message', '添加成功');
        return redirect(route('admin.salesmans.index'));
    }
}
